/**************************************************************************
 *
 * Copyright (C) 2007 University of California, Los Angeles.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *************************************************************************/

/**
 * 
 */
package edu.ucla.cs.typecast.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 *
 * @date Aug 11, 2007
 */
public class NetUtil {
	public static final String LOCALHOST_FILE = "/etc/localhost"; 
	private static InetAddress localHost = null; 
	
	public static InetAddress getLocalHost() { 
		try { 
			if (localHost == null) { 
				NetworkInterface eth1 = NetworkInterface.getByName("eth1"); 
				if (eth1 != null) { 
    				Enumeration<InetAddress> addrs = eth1.getInetAddresses(); 
    				while(addrs.hasMoreElements()) { 
    				    InetAddress addr = addrs.nextElement(); 
    				    if (addr.isLinkLocalAddress()) { 
    				        System.out.println("Link Local address=" + addr.getHostAddress());
    				    } else { 
                            System.out.println("Local address=" + addr.getHostAddress());
    				        localHost = addr; 
    				    }
    				}
				}
				if (localHost == null) {
				    System.out.println("Reading local host IP information from " + LOCALHOST_FILE); 
    				File file = new File(LOCALHOST_FILE); 
    				if (file.canRead()) { 
    					BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    					String ip = reader.readLine().trim(); 
    					localHost = InetAddress.getByName(ip); 
    				}
    				localHost =  InetAddress.getLocalHost();
				}
			}
			return localHost; 
		} catch(Throwable t) { 
			t.printStackTrace(); 
			throw new RuntimeException(t); 
		}
			
	}
	
}	
